package com.example.demo.detailsservice;

import com.example.demo.mapper.PermissionMapper;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Permission;
import com.example.demo.pojo.Role;
import com.example.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * 方法根据用户名查询用户对象，和用户的权限列表
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("自定义登录服务,loadUserByUsername方法执行");
        //根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        //判断用户是否存在
        if (user == null){
            System.out.println("用户名"+username+"不存在");
            //用户不存在
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //开始查询已登录用户的权限集合
        //查询角色
        List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
        //查询权限
        List<Permission> permissions = permissionMapper.selectPermissionByUserId(user.getId());
        //定义一个字符串泛型的list集合对象
        List<String> authorities = new ArrayList<>();
        for (Role role : roles){
            authorities.add("ROLE_"+role.getName());
        }
        for (Permission permission : permissions){
            authorities.add(permission.getPermit());
        }
        System.out.println(authorities);
        //返回UserDetails接口类型对象
        org.springframework.security.core.userdetails.User result
                = new org.springframework.security.core.userdetails.User(
                        user.getUsername(),//登录用户的用户名
                        user.getPassword(),//登录用户的密码.是服务端保存的密文
//                        AuthorityUtils.NO_AUTHORITIES//工具提供的无权限空集合
                        AuthorityUtils.createAuthorityList(authorities)//通过工具,把字符串权限转换成Security定义的权限
                );
        return result;
    }
}
